<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>1. 将 x 减到 0 的最小操作次数</title>
</head>

<body>
  <script>
    var minOperations = function (nums, x) {
      let sum = 0
      for (const num of nums) sum += num

      const target = sum - x, n = nums.length
      let i = 0, j = 0, subsum = 0, ans = -1
      while (j < n) {
        subsum += nums[j]
        while (subsum > target) {
          subsum -= nums[i]
          i++
        }

        if (subsum === target) {
          ans = Math.max(ans, j - i + 1)
        }
        j++
      }
      return ans === -1 ? -1 : n - ans
    };
    console.log(minOperations([1, 1, 4, 2, 3], 5))
  </script>

</body>

</html>